<template>
  <div class="divBox">
    <el-card :bordered="false" shadow="never" class="ivu-mt">
      <el-button
        type="primary"
        size="mini"
        icon="el-icon-circle-plus-outline"
        class="m-bottom-20"
        @click="edit({}, 0)"
        v-hasPermi="['admin:system:group:data:save']"
        >添加图片</el-button
      >
      <el-table border
        :data="tableList"
        v-loading="loading"
        highlight-current-row
        no-userFrom-text="暂无数据"
        no-filtered-userFrom-text="暂无筛选结果"
      >
        <el-table-column label="标题" min-width="100" prop="name">
        </el-table-column>
        <el-table-column label="跳转链接" min-width="100" prop="url">
        </el-table-column>
        <el-table-column label="图片" min-width="100" prop="pic">
          <template slot-scope="scope">
            <el-image
              style="width: 36px; height: 36px"
              :src="scope.row.pic"
              :preview-src-list="[scope.row.pic]"
            />
          </template>
        </el-table-column>
        <el-table-column label="状态" min-width="100" prop="status">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-text="显示"
              inactive-text="隐藏"
              @change="changeStatus(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="edit(scope.row, 1)"
              >编辑</el-button
            >
            <el-button type="text" size="small" @click="handleDel(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="[15, 30, 45, 60]"
          :page-size="tableFrom.limit"
          :current-page="tableFrom.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>

    <el-dialog
      :title="editDataConfig.isCreate === 0 ? '添加数据' : '编辑数据'"
      :visible.sync="dialogVisible"
      append-to-body
      destroy-on-close
      width="700px"
    >
      <edit
        v-if="dialogVisible"
        :form-data="{ id: gid, formId }"
        :edit-data="ruleForm"
        :is-create="ruleForm.isCreate"
        @hideDialog="handlerHideDia"
      />
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import edit from "../../maintain/devconfig/combineEdit";
import {
  bannerList,
  bannerAdd,
  bannerInfo,
  bannerEdit,
  bannerDelete,
} from "@/api/dataField";
export default {
  name: "carousel",
  components: { edit },
  data() {
    return {
      myHeaders: { "X-Token": getToken() },
      //48 95为移动端轮播图表单ID
      gid: 48,
      formId: 95,
      tableFrom: {
        page: 1,
        limit: 15,
      },
      loading: false,
      tableList: [],
      total: 0,
      dialogVisible: false,
      editDataConfig: {},
    };
  },
  mounted() {
    this.getlist();
  },
  methods: {
    add() {
      this.ruleForm = {
        id: "",
        version: "", // 版本号
        isNew: 1, // 是否为线上最新版本（1是 2否）
        platform: 1, // 平台类型（1安卓 2苹果 3PC）
        isForce: 1, // 是否强制（1强制  2非强制）
        url: "", // 下载地址
        info: "", // 升级信息（升级备注）
      };
      this.dialogVisible = true;
    },
    edit(row, isCreate) {
      this.ruleForm = row;
      this.ruleForm.isCreate = isCreate;
      this.dialogVisible = true;
    },
    handleDel(row) {
      this.$confirm("确认删除？")
        .then((_) => {
          console.log("删除", row);
          bannerDelete(row)
            .then((res) => {
              console.log(res);
              this.$message.success("删除成功");
              this.getlist();
            })
            .catch((err) => {
              console.log(err);
              this.$message.error(err);
            });
        })
        .catch((_) => {});
    },
    close() {
      this.ruleForm = {
        id: "",
        version: "", // 版本号
        isNew: "1", // 是否为线上最新版本（1是 2否）
        platform: "1", // 平台类型（1安卓 2苹果 3PC）
        isForce: "1", // 是否强制（1强制  2非强制）
        url: "", // 下载地址
        info: "", // 升级信息（升级备注）
      };
      this.dialogVisible = false;
    },
    submit() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          if (this.ruleForm.id) {
            console.log("编辑", this.ruleForm);
            bannerEdit(this.ruleForm)
              .then((res) => {
                console.log(res);
                this.close();
                this.$message.success("编辑成功");
                this.getlist();
              })
              .catch((err) => {
                console.log(err);
                this.$message.error(err);
              });
          } else {
            console.log("新增", this.ruleForm);
            let data = {
              version: this.ruleForm.version,
              isNew: this.ruleForm.isNew,
              platform: this.ruleForm.platform,
              isForce: this.ruleForm.isForce,
              url: this.ruleForm.url,
              info: this.ruleForm.info,
            };
            bannerAdd(data)
              .then((res) => {
                console.log(res);
                this.close();
                this.$message.success("新增成功");
                this.getlist();
              })
              .catch((err) => {
                console.log(err);
                this.$message.error(err);
              });
          }
        } else {
          this.$message.error("请填写完整信息");
        }
      });
    },
    // 版本信息列表
    getlist() {
      this.loading = true;
      bannerList(this.tableFrom)
        .then((data) => {
          console.log("APP版本列表", data.list);
          const _selfList = [];
          data.list.forEach((_lItem) => {
            _lItem.value = JSON.parse(_lItem.value);
            const _fields = _lItem.value.fields;
            const _rowData = {};
            _fields.map((item) => {
              _rowData[item.name] = item.value;
            });
            _rowData.id = _lItem.id;
            _rowData.sort = _lItem.sort;
            _rowData.status = _lItem.status;
            _selfList.push(_rowData);
          });
          this.tableList = _selfList;
          this.total = data.total;
          // this.tableList = res.list
          // .map((item) =>
          //   JSON.parse(item.value).fields.filter(
          //     (field) => field.name === "pic"
          //   )
          // )
          // .flat();

          console.log("🚀🚀🚀 ~ .then ~ this.tableList:", this.tableList);
          // this.total = res.total;
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
          this.loading = false;
        });
    },
    pageChange(page) {
      this.tableFrom.page = page;
      this.getlist();
    },
    changeStatus(row) {
      let data = this.buildFormPram(row, row.status);
      bannerEdit(data, { id: row.id })
        .then((res) => {
          console.log(res);
          this.$message.success("修改成功");
          this.getlist();
        })
        .catch((err) => {
          console.log(err);
          this.$message.error(err);
        });
    },
    buildFormPram(formValue, status) {
      const _pram = {
        gid: this.gid,
        form: {
          fields: [],
          id: this.formId,
          status,
        },
      };
      const _fields = [];
      Object.keys(formValue).forEach((key) => {
        _fields.push({
          name: key,
          title: key,
          value: formValue[key],
        });
      });
      _pram.form.fields = _fields;
      return _pram;
    },
    handleSizeChange(val) {
      this.tableFrom.limit = val;
      this.getlist();
    },
    handlerHideDia() {
      this.getlist();
      this.dialogVisible = false;
    },
  },
};
</script>

<style scoped lang="scss">
.m-bottom-20{
  margin-bottom: 20px;
}
</style>
